﻿using System;
using System.Windows.Forms;
using System.Configuration;
using System.Reflection;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;

namespace XpoImport
{
    public partial class Main : XtraForm
    {
        public Main()
        {
            InitializeComponent();
        }

        void importer_StepProgress(object sender, EventArgs e)
        {
            importView.RefreshData();
            Application.DoEvents();
        }

        void importer_ImportComplete(object sender, EventArgs e)
        {
            Console.WriteLine("ImportComplete");
            MessageBox.Show("Import Complete.");
        }

        void importer_ImportStarted(object sender, EventArgs e)
        {
            if (sender is ImportBase)
            {
                progressMessage.Caption = ((ImportBase)sender).Name;
            }
        }

        void importer_ImportError(object sender, EventArgs e)
        {
            Console.WriteLine("ImportError");
        }

        private void ProcessImport(string fileName)
        {
            Assembly targetAssembly = null;
            try
            {
                targetAssembly = Assembly.LoadFile(fileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Loading Assembly", ex.Message);
            }
            finally
            {
                if (targetAssembly != null)
                {
                    Importer importer = new Importer(targetAssembly);

                    importer.ImportError += importer_ImportError;
                    importer.ImportStarted += importer_ImportStarted;
                    importer.ImportComplete += importer_ImportComplete;
                    importer.StepProgress += importer_StepProgress;

                    importGrid.DataSource = importer.Imports;

                    importer.StartImport();
                }
            }
        }

        private void fileExit_ItemClick(object sender, ItemClickEventArgs e)
        {
            Environment.Exit(0);
        }

        private void fileOpen_ItemClick(object sender, ItemClickEventArgs e)
        {
            openDialog.FileName = ConfigurationManager.AppSettings["TargetAssembly"];
            
            DialogResult dialogResult = openDialog.ShowDialog();

            if (dialogResult == System.Windows.Forms.DialogResult.OK && System.IO.File.Exists(openDialog.FileName))
            {
                ProcessImport(openDialog.FileName);
            }
        }

    }
}